package cn.juni.controller;

import cn.juni.pojo.Product;
import cn.juni.service.IProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;
import java.util.UUID;

/**
 * @author Juni
 * @date 2021/2/22
 *  String          返回视图名
 *  ModelAndView    返回视图+数据
 *  实体对象          Ajax请求
 */
@Controller
@RequestMapping("/product")
//@RestController = @Controller+@ResponseBody
public class ProductController {

    @Autowired
    IProductService productService;

    /**
     * 前台页面需要分页的所有信息（当前页、每页的条数、当前页的数据、总条数、总页数等等），都在PageInfo对象中
     * @RolesAllowed 该注解会自动省略掉前缀
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/findAllProduct")
    public String findAllProduct(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "3") Integer pageSize,
            Product product,
            Model model){
        //产品列表的数据
        List<Product> productList = productService.findAllProduct(pageNum,pageSize,product);
        //通过分页拿到的productList，其实是一个Page对象，通过构造器出入该对象后会对其进行判断，然后将值付给PageInfo中的属性
        PageInfo pageInfo = new PageInfo(productList);
        model.addAttribute("pageInfo",pageInfo);
        return "product-list";
    }

    @RequestMapping("/saveProduct")
    public String insertProduct(Product product){
        //生成UUID作为id字段的值
        String id = UUID.randomUUID().toString().replace("-","");
        product.setId(id);
        productService.insertProduct(product);
        return "redirect:findAllProduct";
    }

    @RequestMapping("deleteProductById")
    public String deleteProductById(String id){
        productService.deleteProductById(id);
        return "redirect:findAllProduct";
    }

}
